import xadmin
import xadmin.views as xviews
from xadmin.plugins.actions import BaseActionView, DeleteSelectedAction as ODeleteSelectedAction
from django.core.exceptions import PermissionDenied
from django_celery_beat.models import PeriodicTask, IntervalSchedule, CrontabSchedule
from django.urls import reverse
from django.conf.urls import url
from django.shortcuts import get_object_or_404
from django.http import JsonResponse
from django.utils.translation import ugettext_lazy as _
from django_celery_beat.admin import PeriodicTaskForm
import json

# override model field's setting(Your can'nt inherit to override)
PeriodicTask._meta.get_field('date_changed').verbose_name = _('Date changed')
PeriodicTask._meta.get_field('total_run_count').verbose_name = _('Total run count')
PeriodicTask._meta.get_field('last_run_at').verbose_name = _('Last run at')
PeriodicTask._meta.get_field('task').default = 'command'


# theme
class BaseSetting(object):
    enable_themes = True
    use_bootswatch = True


# admin site setting
class GlobalSetting(object):
    site_title = "恒易融任务调度平台"
    site_footer = "恒易融"
    menu_style = "accordion"


# xadmin.PeriodicTaskAdmin.actions[]
class DisableSelectedAction(BaseActionView):
    action_name = 'disable_selected'
    description = '禁用选中'

    def do_action(self, queryset):
        if not self.has_change_permission():
            raise PermissionDenied
        if self.request.method == 'POST':
            for object in queryset:
                object.enabled = False
                object.save()
            self.message_user('设置成功', 'success')


# xadmin.PeriodicTaskAdmin.actions[]
class DeleteSelectedAction(ODeleteSelectedAction):
    description = '删除选中'


class PeriodicTaskAdmin(object):
    model_icon = 'fa fa-clock-o'  # 图标
    # form = PeriodicTaskForm #TODO 表单美化
    # model = PeriodicTask
    search_fields = ('name', 'args')  # 搜索
    show_detail_fields = ('get_name',)  # 显示详情
    list_display = (
        'get_name', 'task', 'rule', 'args', 'enabled', 'get_date_changed', 'total_run_count', 'get_last_run_at',
        'single_column_action',)
    list_filter = ('total_run_count', 'last_run_at',)  # 过滤器
    list_editable = ('enabled',)  # 可编辑字段
    ordering = ('-id',)  # 默认排序字段
    global_actions = []  # 禁用默认的 DeleteSelectedAction
    actions = [DeleteSelectedAction, DisableSelectedAction]  # 自定义动作

    def rule(self, obj):
        if obj.crontab:
            return obj.crontab
        else:
            period_dict = {'days': '天', 'hours': '小时', 'minutes': '分钟', 'seconds': '秒', 'microseconds': '微秒'}
            return '每' + str(obj.interval.every) + period_dict[obj.interval.period]

    rule.short_description = "规则"

    def get_name(self, obj):
        return obj.name

    get_name.short_description = '标题'
    get_name.admin_order_field = 'name'  # can sortable

    def get_date_changed(self, obj):
        return obj.date_changed.strftime('%Y-%m-%d %H:%M:%S')

    get_date_changed.short_description = '修改日期'
    get_date_changed.admin_order_field = 'date_changed'  # can sortable

    def get_last_run_at(self, obj):
        return obj.last_run_at.strftime('%Y-%m-%d %H:%M:%S') if obj.last_run_at else '--'

    get_last_run_at.short_description = _('Last run at')
    get_last_run_at.admin_order_field = 'last_run_at'  # can sortable

    # 新增一功能列
    def single_column_action(self, obj):
        return '<button class="btn btn-info btn-mini trigger_task" data-href="{}">立即执行</button><a class="btn btn-info btn-small" href="{}" target="_blank">执行记录</a>'.format(
            reverse('xadmin:manual_trigger_task', args=[obj.pk, ]), 'http://10.100.14.27:5555/')

    single_column_action.short_description = '操作'
    single_column_action.allow_tags = True

    def get_media(self):
        # media is the parent's return value (modified by any plugins)
        media = super(PeriodicTaskAdmin, self).get_media()
        media.add_js(('/static/proj/js/django_celery_beat.js',))
        return media


class ManualTriggerTaskView(xviews.CommAdminView):
    def get(self, request, pk):
        """
            手工触发任务
        """
        # 权限检查
        if not (request.user.is_authenticated() and request.user.has_perm('django_celery_beat.manual_trigger_task')):
            from django.contrib.auth import PermissionDenied
            raise PermissionDenied()
        p = get_object_or_404(PeriodicTask, pk=int(pk))
        import importlib
        module_name = importlib.import_module('proj.tasks')  # 动态加载模块
        func_name = p.task  # 模块中的函数名
        func_args = json.loads(p.args)  # 参数
        if hasattr(module_name, func_name):
            func = getattr(module_name, func_name)  # 获取函数指针
            func.delay(*func_args)  # 调用（这里暂时不做异常处理try except else finally）
            return JsonResponse({'success': 1})
        else:
            raise AttributeError()


xadmin.site.register(PeriodicTask, PeriodicTaskAdmin)
xadmin.site.register(IntervalSchedule)
xadmin.site.register(CrontabSchedule)
xadmin.site.register(xviews.BaseAdminView, BaseSetting)
xadmin.site.register(xviews.CommAdminView, GlobalSetting)
xadmin.site.register_view(r'^xadmin/django_celery_beat/periodictask/(?P<pk>\d+)/manual_trigger/$',
                          ManualTriggerTaskView, name='manual_trigger_task')
